//
//  GroupViewController.swift
//  puretennis
//
//  Created by IYE Technologies on 11/9/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit

class GroupViewController: UIViewController,UITabBarControllerDelegate {
    var internetReachability:Reachability!;
    var notReachableView:UIButton?;
    
    var totalPages = 1;
    var currentPageNumber = 1;
    var groupTableView: UITableView!
    var groupsTableViewDataSourceAndDelegate:GroupsTableViewDataSourceAndDelegate!;
    
    var margin:CGFloat = 5;
    
    override func viewDidLoad() {
        super.viewDidLoad();
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("reachabilityChanged:"), name: kReachabilityChangedNotification, object: nil);
        self.internetReachability = Reachability.reachabilityForInternetConnection();
        self.internetReachability.startNotifier();
        self.initNavigationBar();
    }
    
    func initGroupTableView(){
        if(self.groupTableView == nil){
            var statusBarHeight = ViewUtils.statusBarHeight();
            var navBarHeight = self.navBarHeight();
            var tabBarHeight = self.tabBarHeight();
            
            var tableViewY = statusBarHeight + navBarHeight! + margin;
            var tableViewWidth = self.view.frame.width - margin * 2;
            var tableViewHeight = self.view.frame.height - (tableViewY + tabBarHeight!);
            var tableVieFrame = CGRect(x: margin, y: tableViewY, width: tableViewWidth, height: tableViewHeight);
            self.groupTableView = UITableView(frame: tableVieFrame);
            self.groupTableView.separatorStyle = UITableViewCellSeparatorStyle.None;
            self.groupTableView.backgroundColor = UIColor.clearColor();
            self.groupsTableViewDataSourceAndDelegate = GroupsTableViewDataSourceAndDelegate();
            self.groupTableView.dataSource = self.groupsTableViewDataSourceAndDelegate;
            self.groupTableView.delegate = self.groupsTableViewDataSourceAndDelegate;
            self.view.addSubview(self.groupTableView);
        }
    }
    
    func reachabilityChanged(notification:NSNotification){
        self.internetReachability = notification.object! as Reachability;
        var status = self.internetReachability.currentReachabilityStatus();
        
        if(status.value == NotReachable.value){
            self.showNotReachableVeiw();
        } else {
            self.hideNotReachableView();
        }
    }
    
    func initNavigationBar(){
        self.navigationItem.titleView = ViewUtils.titleView("我的群");
        var createGroupButton = UIButton();
        createGroupButton.setImage(UIImage(named: "add"), forState: UIControlState.Normal);
        createGroupButton.contentMode = UIViewContentMode.Right;
        createGroupButton.showsTouchWhenHighlighted = true;
        createGroupButton.sizeToFit();
        createGroupButton.addTarget(self, action: Selector("searchGroup:"), forControlEvents: UIControlEvents.TouchUpInside);
        var createGroupItem = UIBarButtonItem(customView: createGroupButton);
        self.navigationItem.rightBarButtonItem = createGroupItem;
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated);
        self.initGroupTableView();
        var status = self.internetReachability.currentReachabilityStatus();
        if(status.value == NotReachable.value){
            self.showNotReachableVeiw();
        } else {
            self.hideNotReachableView();
        }
        self.showTabBar();
        self.groupsTableViewDataSourceAndDelegate.navigationController(self.navigationController!);
        
        self.loadGroups();
    }
    
    
    func showNotReachableVeiw(){
        if(self.notReachableView == nil){
            var height:CGFloat = 40;
            var tableOrigin = self.groupTableView.frame.origin;
            var size = CGSize(width: self.groupTableView.frame.width, height: height);
            var frame = CGRect(origin: tableOrigin, size: size);
            
            self.notReachableView = UIButton(frame: frame);
            self.notReachableView!.backgroundColor = UIColor.yellowColor();
            self.notReachableView!.layer.masksToBounds = true;
            self.notReachableView!.layer.cornerRadius = 4;
            
            var alertImageMargin:CGFloat = 10;
            var alertFrame = CGRect(x: alertImageMargin, y: alertImageMargin, width: height - alertImageMargin * 2, height: height - alertImageMargin * 2);
            var alertImageView = UIImageView(image: UIImage(named: "alert")!);
            alertImageView.frame = alertFrame;
            self.notReachableView!.addSubview(alertImageView);
            
            var labelFrame = CGRect(x: alertFrame.origin.x + alertFrame.width + alertImageMargin, y: 0, width: self.notReachableView!.frame.width - alertImageMargin * 2, height: height);
            var label = UILabel(frame: labelFrame);
            label.text = "世界上最遥远的距离就是没网,检查网络";
            label.textColor = UIColor.whiteColor();
            label.font = Utils.fontHupo(14);
            self.notReachableView!.addSubview(label);
            self.notReachableView?.addTarget(self, action: Selector("networkSetting:"), forControlEvents: UIControlEvents.TouchUpInside);
            self.view.addSubview(self.notReachableView!);
            self.groupTableView.frame.origin.y = tableOrigin.y + height + self.margin;
            self.groupTableView.frame.size.height = self.groupTableView.frame.height - height;
        }
    }
    
    func networkSetting(sender:UIButton){
        var storyboard = UIStoryboard(name: "Main", bundle: nil);
        var notworkSettingReferenceController = storyboard.instantiateViewControllerWithIdentifier("notworkSettingReferenceView") as NotworkSettingReferenceController;
        self.navigationController?.pushViewController(notworkSettingReferenceController, animated: true);
    }
    
    func hideNotReachableView(){
        if(self.notReachableView != nil){
            var tableViewOffset = self.notReachableView!.frame.height + margin;
            self.groupTableView.frame.origin.y = self.groupTableView.frame.origin.y - tableViewOffset;
            self.groupTableView.frame.size.height = self.groupTableView.frame.height + tableViewOffset;
            self.notReachableView?.removeFromSuperview();
            self.notReachableView = nil;
        }
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated);
        GlobalVariables.groupViewController = self
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        GlobalVariables.groupViewController = nil
    }
    
    // Search group action handler
    func searchGroup(barButtonItem:UIBarButtonItem){
        var storyboard = UIStoryboard(name: "Main", bundle: nil);
        var searchGroupViewController = storyboard.instantiateViewControllerWithIdentifier("searchGroupView") as SearchGroupViewController;
        self.navigationController?.pushViewController(searchGroupViewController, animated: true);
    }
    
    //Load groups
    func loadGroups(){
        self.processing();
        if(currentPageNumber > totalPages){
            self.currentPageNumber = totalPages;
        }
        
        let url = "/api/v1/groups?currentPageNumber=\(currentPageNumber)&itemsPerPage=\(Properties.ITEMS_PER_PAGE)";
        HttpUtils.sendRequest(url, method: RequestMethod.GET, httpBody: nil, successHandle: { (response) -> Void in
            var groupDictionary = response as NSMutableDictionary;
            var groups = groupDictionary.objectForKey("groups") as [NSDictionary];
            self.groupsTableViewDataSourceAndDelegate.groups = groups;
            self.groupTableView.reloadData();
            var currentPageNumber = groupDictionary.objectForKey("currentPageNumber") as Int;
            self.currentPageNumber = currentPageNumber;
            self.processComplete();
            }, errorHandle: { (error) -> Void in
               self.processComplete();
        });
    }

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning();
        Utils.debug("Memory warning")
    }
}
